package com.example.spring.json.config;

import com.google.gson.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import springfox.documentation.spring.web.json.Json;

import java.lang.reflect.Modifier;
import java.lang.reflect.Type;

/**
 * @author : zhayh
 * @date : 2021-3-2 08:47
 * @description :
 */

@Configuration
public class GsonConfig {
    @Bean
    public GsonHttpMessageConverter gsonConverters() {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd")
                .excludeFieldsWithModifiers(Modifier.PROTECTED)  // 对使用特定修饰符排序字段进行控制
                .disableHtmlEscaping()
                .registerTypeAdapter(Json.class, new SwaggerJsonTypeAdapter())  // 注册Swagger的json自定义转换器
                .create();
        converter.setGson(gson);
        return converter;
    }

    // swagger的json转换自定义
    public static class SwaggerJsonTypeAdapter implements JsonSerializer<Json> {

        @Override
        public JsonElement serialize(Json json, Type type, JsonSerializationContext jsonSerializationContext) {
            return JsonParser.parseString(json.value());
        }
    }
}
